<script setup>
import {ref} from "vue";
import requestUtil, {getServerUrl} from "@/utils/request";
import {ElMessage} from "element-plus";
import {Plus} from "@element-plus/icons-vue"
import store from "@/store";
import Cookies from "js-cookie";

const props = defineProps({
  user: {
    type: Object,
    default: () => {
    },
    required: true
  }
})
const headers = ref({
  Authorization: Cookies.get('token')
})

const form = ref({
  id: -1,
  avatar: '',
})
const formRef = ref(null);

const imgUrl = ref("")

form.value = props.user

const uploadRes = ref('')
const disabled = ref(true);
imgUrl.value = getServerUrl() + "media/userAvatar/" + form.value.avatar

const handleAvatarSuccess = (res) => {
  imgUrl.value = getServerUrl() + "media/userAvatar/" + res.title
  form.value.avatar = res.title
  uploadRes.value = res.title
  disabled.value = false;
}
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('图片必须是jpg格式')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2M!')
  }
  return isJPG && isLt2M
}

const handleConfirm = async () => {
  let result = await requestUtil.post("user/update/avatar", form.value)
  let data = result.data
  if (data.code === 200) {
    ElMessage.success("修改成功")

    //将avatar头像名设置到store的imgUrl中，用来同步修改header栏的头像
    store.commit('SET_IMG_URL', imgUrl.value)
    const currentUser = JSON.parse(localStorage.getItem('currentUser'))
    currentUser.avatar = uploadRes.value
    console.log(uploadRes.value)
    localStorage.setItem('currentUser', JSON.stringify(currentUser))
    console.log(currentUser)
  } else {
    ElMessage.error(data.msg)
  }
  disabled.value = true
}
</script>

<template>
  <el-form
      ref="formRef"
      :model="form"
      label-width="100px"
      style="text-align: center;padding-bottom: 10px"
  >
    <el-upload
        name="avatar"
        :headers="headers"
        class="avatar-uploader"
        :action="getServerUrl()+'user/upload/img'"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
      <img v-if="imgUrl" :src="imgUrl" class="avatar"/>
      <el-icon v-else class="avatar-uploader-icon">
        <Plus/>
      </el-icon>
    </el-upload>
    <el-button :disabled="disabled" @click="handleConfirm">确认更换</el-button>
  </el-form>
</template>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
